import { defineComponent, ref, resolveDirective, withDirectives } from 'vue'
import { ElButton, ElDialog, ElMessage, ElMessageBox, ElOption, ElRow, ElTooltip } from 'element-plus'
import { createForm, isField, onFieldInit } from '@formily/core'
import { FormGrid, FormItem, FormLayout, Input, Password, Select } from '@formily/element-plus'
import type { User } from '@/types/user'
import { addUser, getUser, listUser, resetUserPwd, updateUser } from '@/api/system/user'
import DictTag from '@/components/DictTag/index.vue'
import usePageTable from '@/hooks/usePageTable'
import { useDict } from '@/utils/dict'
import SchemaForm from '@/components/SchemaForm'
import { teacherSchema } from '@/views/teacher/list/schema/teacherSchema'

export default defineComponent({
  setup() {
    const { sys_user_sex, sys_teacher_status } = useDict('sys_user_sex', 'sys_teacher_status')
    const hasPermi = resolveDirective('hasPermi')

    /** 列表逻辑 */
    const { QueryForm, Table, handleSearch } = usePageTable<User>(
      {
        getList: listUser,
        fields: [
          {
            title: '身份证号',
            key: 'userName',
            type: 'Input',
          },
          {
            title: '姓名',
            key: 'nickName',
            type: 'Input',
          },
          {
            title: '状态',
            key: 'status',
            type: 'Select',
            enums: () => sys_teacher_status.value.map(
              item =>
                <ElOption label={item.label} value={item.value} key={item.value}>{item.label}</ElOption>,
            ),
          },
        ],
        initValues: {
          userType: '教师',
          pageSize: 10,
          pageNum: 1,
        },
      },
      [
        {
          key: 'userName',
          title: '身份证号',
          props: {
            align: 'center',
          },
        },
        {
          key: 'nickName',
          title: '姓名',
        },
        {
          key: 'sex',
          title: '性别',
          render: row => <DictTag value={row.sex} options={sys_user_sex.value} />,
        },
        {
          key: 'phonenumber',
          title: '手机号码',
        },
        {
          key: 'status',
          title: '状态',
          render: row => <DictTag value={row.status} options={sys_teacher_status.value} />,
        },
        {
          key: 'remark',
          title: '情况说明',
        },
        {
          key: 'operate',
          title: '操作',
          render: row => (
            row.userId !== 1 && (
              <>
                <ElTooltip content="修改" placement="top">
                  {withDirectives(<ElButton
                    link
                    type="primary"
                    icon="Edit"
                    onClick={() => handleUpdate(row)}
                                  />, [[hasPermi, ['system:user:edit']]])}
                </ElTooltip>
                <ElTooltip content="重置密码" placement="top">
                  {withDirectives(<ElButton
                    link
                    type="primary"
                    icon="Key"
                    onClick={() => handleResetPwd(row)}
                                  />, [[hasPermi, ['system:user:resetPwd']]])}
                </ElTooltip>
              </>
            )
          ),
        },
      ],
    )
    void handleSearch()

    /** 新增修改逻辑 */
    const open = ref(false)
    const title = ref('')
    const form = createForm<Partial<User>>({
      effects: () => {
        onFieldInit('layout.gird.sex', (field) => {
          if (isField(field))
            field.dataSource = sys_user_sex.value
        })
        onFieldInit('layout.gird.status', (field) => {
          if (isField(field))
            field.dataSource = sys_teacher_status.value
        })
      },
    })
    async function submitForm() {
      await form.submit((values) => {
        if (values.userId)
          return updateUser(values as Partial<User> & { useId: number })
        return addUser({ ...values, userType: '教师' })
      })
      open.value = false
      void handleSearch()
    }
    function handleAdd() {
      form.setValues({}, 'overwrite')
      open.value = true
      title.value = '新增老师信息'
    }
    async function handleUpdate(row: User) {
      const userId = row.userId
      const { data } = await getUser(userId)
      form.setValues(data, 'overwrite')
      open.value = true
      title.value = '修改老师信息'
    }

    /** 列表操作 */
    async function handleResetPwd(row: User) {
      const { action, value } = await ElMessageBox.prompt(`请输入"${row.userName}"的新密码`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: '用户密码长度必须介于 5 和 20 之间',
      })
      if (action === 'confirm') {
        await resetUserPwd(row.userId, value)
        ElMessage.success(`修改成功，新密码是：${value}`)
      }
    }

    return () => (
      <div class="p-2 md:p-4 h-full flex flex-col">
        <QueryForm />
        <ElRow gutter={10} class="mb-4">
          <ElButton
            type="primary"
            plain
            icon="Plus"
            onClick={handleAdd}
          >
            新增
          </ElButton>
        </ElRow>
        <Table />

        <ElDialog v-model={open.value} title={title.value} width="750px" append-to-body>
          {{
            default: () => (
              <SchemaForm
                form={form}
                schema={teacherSchema}
                components={{ FormGrid, Input, Select, FormItem, FormLayout, Password }}
              />
            ),
            footer: () => (
              <div class="dialog-footer">
                <ElButton type="primary" onClick={submitForm}>
                  确 定
                </ElButton>
                <ElButton onClick={() => open.value = false}>
                  取 消
                </ElButton>
              </div>
            ),
          }}
        </ElDialog>
      </div>
    )
  },
})
